package week9;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 *
 * 151. 翻转字符串里的单词
 * https://leetcode-cn.com/problems/reverse-words-in-a-string/
 *
 * 执行结果：  通过  显示详情
 *
 * 添加备注
 * 执行用时：7 ms, 在所有 Java 提交中击败了59.41% 的用户
 * 内存消耗：38.3 MB, 在所有 Java 提交中击败了86.75% 的用户
 * 通过测试用例：57 / 57
 * 炫耀一下:
 *
 *
 */
public class Week9ReverseWordsInAString {

    public String reverseWords(String s) {
        int left = 0;
        int right = s.length() - 1;

        for(;left <= right && s.charAt(left) == ' ';) {
            left++;
        }

        for(;left <= right && s.charAt(right) == ' ';) {
            right--;
        }

        Deque<String> d = new ArrayDeque<String>();
        StringBuilder word = new StringBuilder();

        for(;left <= right;) {
            char c = s.charAt(left);
            if((word.length() != 0) && (c == ' ')) {
                d.offerFirst(word.toString());
                word.setLength(0);
            } else if(c != ' ') {
                word.append(c);
            }
            left++;
        }
        d.offerFirst(word.toString());
        return s.join(" ", d);

    }
}
